package com.smm.web.vmc.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.smm.web.vmc.tool.HttpRequest;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

@Slf4j
public class YSApi {
    public static String accessToken;
    private static final long maxTime = 604800000L;
    private static long preTokenTime = 0L;
    private static final String appKey = "8079c556154c4953afea18596bf6c9ab";
    private static final String secret = "bd7d1ac76160cf6036fd507cb131b2bb";



    /**
     * 抓拍接口
     * @param deviceSerial
     * @return
     * @throws Exception
     */
    public static String capture(String deviceSerial)
            throws Exception {
        String token = getToken();

        String result = HttpRequest.sendPost("https://open.ys7.com/api/lapp/device/capture", "accessToken=" + token + "&deviceSerial=" + deviceSerial + "&channelNo=1&quality=1");

        JSONObject object = JSON.parseObject(result);

        int code = object.getInteger("code").intValue();

        if (code != 200) throw new Exception("萤石云api访问失败。code:" + code);

        JSONObject data = object.getJSONObject("data");

        log.info("萤石云抓拍成功，返回信息:");

        log.info(data.toJSONString());

        return data.getString("picUrl");
    }

    public static String getToken()
            throws Exception {
        boolean isDisable = checkToken();

        if (isDisable) {
            String result = HttpRequest.sendPost("https://open.ys7.com/api/lapp/token/get", "appKey=8079c556154c4953afea18596bf6c9ab&appSecret=bd7d1ac76160cf6036fd507cb131b2bb");

            JSONObject object = JSON.parseObject(result);

            int code = object.getInteger("code").intValue();

            if (code != 200) throw new Exception("萤石云api访问失败。code:" + code);

            JSONObject data = object.getJSONObject("data");

            accessToken = data.getString("accessToken");

            preTokenTime = new Date().getTime();
        }

        return accessToken;
    }

    private static boolean checkToken() {
        if (preTokenTime == 0L) return true;

        long nowTime = new Date().getTime();

        long tagetTime = preTokenTime + 604800000L;

        return tagetTime <= nowTime;
    }

    public static void main(String[] args) {
        String result = HttpRequest.sendPost("https://open.ys7.com/api/lapp/token/get", "appKey=8079c556154c4953afea18596bf6c9ab&appSecret=bd7d1ac76160cf6036fd507cb131b2bb");
        System.out.println(result);

        JSONObject object = JSON.parseObject(result);

        System.out.println(object.getInteger("code"));
        System.out.println(object.getString("msg"));

        JSONObject data = object.getJSONObject("data");

        System.out.println(data.getString("accessToken"));
    }
}